﻿using UnityEngine;
using UnityEditor;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;


public class AnimationClipData {
	public string path;
	public string property;
	public bool selected;

	public AnimationClipData(string path, string property) {
		this.path = path;
		this.property = property;
		this.selected = false;
	}
}

public class AnimationSplit {
	static string projectRoot = Path.GetDirectoryName(Application.dataPath);
	static string defaultTargeAnimPath = "Assets";
	public string targetPath;

	public string[] animations {
		get;private set;
	}
	public List<AnimationClipData> animInfos{
		get;private set;
	}

	public AnimationClipCurveData[] curves {
		get; private set;
	}

	public void GetAllAnimations(string path) {
		animations = Directory.GetFiles(path, "*.anim", SearchOption.AllDirectories);
	}

	public void LoadCurves(string file) {
		Regex regex = new Regex("Assets/.*\\.anim$", RegexOptions.None);
		Match match = regex.Match(file);
	
		targetPath = string.Format("{0}/{1}", defaultTargeAnimPath, Path.GetFileName(file));
		curves = null;
		if (match.Success) {
			AnimationClip clip = AssetDatabase.LoadAssetAtPath(match.Value, typeof(AnimationClip)) as AnimationClip;
			if (null != clip) {
				curves = AnimationUtility.GetAllCurves(clip);
				if (animInfos == null) {
					animInfos = new List<AnimationClipData>();
				} else {
					animInfos.Clear();
				}
				foreach(AnimationClipCurveData data in curves) {
					animInfos.Add(new AnimationClipData(data.path, data.propertyName));
				}
				//cannot find unload assets API
				//maybe we should add something like Resources.UnloadUnusedAssets().
			} else {
				Debug.LogError(string.Format("load {0} failed", match.Groups[1].Value));
			}
		} else {
			Debug.LogError(string.Format("cannot match {0}", file));
		}
	}

	public void UpdateSelectInfo(bool select) {
		foreach(AnimationClipData data in animInfos) {
			data.selected = select;
		}
	}

	public void ExportClip() {
		int count = 0;
		foreach(AnimationClipData data in animInfos) {
			if (data.selected) {
				++count;
			}
		}

		if (count > 0) {
			AnimationClip clip = new AnimationClip();
			if (curves.Length != animInfos.Count) {
				Debug.LogError(string.Format("curves doesn't match the animInfos"));
				return;
			}

			for(int i = 0; i< animInfos.Count; ++i) {
				if (animInfos[i].selected) {
					clip.SetCurve(animInfos[i].path, curves[i].type, animInfos[i].property, curves[i].curve);
				}
			}
			Debug.Log(targetPath);
			AssetDatabase.CreateAsset(clip, targetPath);
		} else {
			Debug.Log(string.Format("no curve seleted"));
		}
	}

}
	